<template>
	<div class="exception-detail">
		<!-- 异常基本信息 -->
		<el-card shadow="never" class="detail-card">
			<template #header>
				<div class="card-header">
				<span>基本信息</span>
				<el-tag :type="getExceptionLevelTagType(exceptionData.exceptionLevel)" size="small">
					{{ getExceptionLevelLabel(exceptionData.exceptionLevel) }}
				</el-tag>
				</div>
			</template>
			<el-descriptions :column="2" border>
				<el-descriptions-item label="异常ID">{{ exceptionData.id }}</el-descriptions-item>
				<el-descriptions-item label="异常类型">
					<el-tag :type="getExceptionTypeTagType(exceptionData.exceptionType)" size="small">
						{{ getExceptionTypeLabel(exceptionData.exceptionType) }}
					</el-tag>
				</el-descriptions-item>
				<el-descriptions-item label="模块名称">{{ exceptionData.moduleName }}</el-descriptions-item>
				<el-descriptions-item label="方法名称">{{ exceptionData.methodName }}</el-descriptions-item>
				<el-descriptions-item label="发生时间">{{ formatDateTime(exceptionData.createdAt) }}</el-descriptions-item>
				<el-descriptions-item label="处理状态">
					<el-tag :type="getHandleStatusTagType(exceptionData.handleStatus)" size="small">
						{{ getHandleStatusLabel(exceptionData.handleStatus) }}
					</el-tag>
				</el-descriptions-item>
				<el-descriptions-item label="处理人" v-if="exceptionData.handledBy">{{ exceptionData.handledBy }}</el-descriptions-item>
				<el-descriptions-item label="处理时间" v-if="exceptionData.handledAt">{{ formatDateTime(exceptionData.handledAt) }}</el-descriptions-item>
			</el-descriptions>
		</el-card>

		<!-- 异常信息 -->
		<el-card shadow="never" class="detail-card">
			<template #header>
				<div class="card-header">
				<span>异常信息</span>
				<el-button type="text" size="small" @click="toggleMessageExpand">
					{{ messageExpanded ? '收起' : '展开' }}
					<i :class="messageExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
				</el-button>
				</div>
			</template>
			<div class="exception-message" :class="{ expanded: messageExpanded }">
				{{ exceptionData.exceptionMessage }}
			</div>
		</el-card>

		<!-- 堆栈信息 -->
		<el-card shadow="never" class="detail-card">
			<template #header>
				<div class="card-header">
				<span>堆栈信息</span>
				<el-button type="text" size="small" @click="toggleStackExpand">
					{{ stackExpanded ? '收起' : '展开' }}
					<i :class="stackExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
				</el-button>
				<el-button type="text" size="small" @click="copyStackTrace">
					<i class="el-icon-document-copy"></i> 复制
				</el-button>
				</div>
			</template>
			<div class="stack-trace" :class="{ expanded: stackExpanded }">
				<pre>{{ exceptionData.stackTrace }}</pre>
			</div>
		</el-card>

		<!-- 请求参数 -->
		<el-card shadow="never" class="detail-card" v-if="exceptionData.requestParams">
			<template #header>
				<div class="card-header">
				<span>请求参数</span>
				<el-button type="text" size="small" @click="formatRequestParams">
					<i class="el-icon-magic-stick"></i> 格式化
				</el-button>
				</div>
			</template>
			<div class="request-params">
				<pre>{{ formattedParams }}</pre>
			</div>
		</el-card>

		<!-- 用户信息 -->
		<el-card shadow="never" class="detail-card" v-if="exceptionData.userInfo">
			<template #header>
				<span>用户信息</span>
			</template>
			<el-descriptions :column="2" border>
				<el-descriptions-item label="用户ID">{{ exceptionData.userInfo.userId }}</el-descriptions-item>
				<el-descriptions-item label="用户名">{{ exceptionData.userInfo.username }}</el-descriptions-item>
				<el-descriptions-item label="真实姓名">{{ exceptionData.userInfo.realName }}</el-descriptions-item>
				<el-descriptions-item label="用户角色">{{ exceptionData.userInfo.userRole }}</el-descriptions-item>
				<el-descriptions-item label="IP地址">{{ exceptionData.userInfo.ipAddress }}</el-descriptions-item>
				<el-descriptions-item label="设备信息">{{ exceptionData.userInfo.userAgent }}</el-descriptions-item>
			</el-descriptions>
		</el-card>

		<!-- 环境信息 -->
		<el-card shadow="never" class="detail-card" v-if="exceptionData.environmentInfo">
			<template #header>
				<span>环境信息</span>
			</template>
			<el-descriptions :column="2" border>
				<el-descriptions-item label="服务名称">{{ exceptionData.environmentInfo.serviceName }}</el-descriptions-item>
				<el-descriptions-item label="服务版本">{{ exceptionData.environmentInfo.serviceVersion }}</el-descriptions-item>
				<el-descriptions-item label="服务器IP">{{ exceptionData.environmentInfo.serverIp }}</el-descriptions-item>
				<el-descriptions-item label="操作系统">{{ exceptionData.environmentInfo.osName }}</el-descriptions-item>
				<el-descriptions-item label="Java版本">{{ exceptionData.environmentInfo.javaVersion }}</el-descriptions-item>
				<el-descriptions-item label="Spring版本">{{ exceptionData.environmentInfo.springVersion }}</el-descriptions-item>
			</el-descriptions>
		</el-card>

		<!-- 处理记录 -->
		<el-card shadow="never" class="detail-card">
			<template #header>
				<div class="card-header">
					<span>处理记录</span>
					<el-button type="primary" size="small" @click="showAddRecordDialog" v-if="exceptionData.handleStatus !== 'HANDLED'">
						<i class="el-icon-plus"></i> 添加处理记录
					</el-button>
				</div>
			</template>
			<el-timeline>
				<el-timeline-item
					v-for="record in handlingRecords"
					:key="record.id"
					:timestamp="formatDateTime(record.createdAt)"
					:color="getRecordColor(record.action)">
					<div class="record-content">
						<div class="record-header">
							<span class="record-user">{{ record.createdBy }}</span>
							<el-tag :type="getActionTagType(record.action)" size="small">
								{{ getActionLabel(record.action) }}
							</el-tag>
						</div>
						<div class="record-remark" v-if="record.remark">{{ record.remark }}</div>
					</div>
				</el-timeline-item>
			</el-timeline>
		</el-card>

		<!-- 解决方案 -->
		<el-card shadow="never" class="detail-card" v-if="exceptionData.solution">
			<template #header>
				<span>解决方案</span>
			</template>
			<div class="solution-content">
				<div class="solution-text">{{ exceptionData.solution }}</div>
				<div class="solution-meta" v-if="exceptionData.solutionAuthor">
					<span>提供者：{{ exceptionData.solutionAuthor }}</span>
					<span>更新时间：{{ formatDateTime(exceptionData.solutionUpdatedAt) }}</span>
				</div>
			</div>
		</el-card>

		<!-- 相关异常 -->
		<el-card shadow="never" class="detail-card" v-if="relatedExceptions.length > 0">
			<template #header>
				<span>相关异常</span>
			</template>
			<el-table :data="relatedExceptions" size="small">
				<el-table-column prop="id" label="ID" width="80"></el-table-column>
				<el-table-column prop="exceptionType" label="类型" width="120">
					<template #default="scope">
						<el-tag :type="getExceptionTypeTagType(scope.row.exceptionType)" size="mini">
							{{ getExceptionTypeLabel(scope.row.exceptionType) }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="exceptionMessage" label="异常信息" min-width="200" show-overflow-tooltip></el-table-column>
				<el-table-column prop="moduleName" label="模块" width="120"></el-table-column>
				<el-table-column prop="createdAt" label="时间" width="180">
					<template #default="scope">
						{{ formatDateTime(scope.row.createdAt) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="100">
					<template #default="scope">
						<el-button type="text" size="small" @click="viewRelatedException(scope.row)">查看</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<!-- 添加处理记录对话框 -->
		<el-dialog
			title="添加处理记录"
			v-model="addRecordDialogVisible"
			width="600px">
			<el-form :model="recordForm" :rules="recordFormRules" ref="recordFormRef" label-width="100px">
				<el-form-item label="处理动作" prop="action">
					<el-radio-group v-model="recordForm.action">
						<el-radio label="ANALYZE">分析</el-radio>
						<el-radio label="SOLVE">解决</el-radio>
						<el-radio label="CLOSE">关闭</el-radio>
						<el-radio label="REOPEN">重新打开</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="处理备注" prop="remark">
					<el-input
						v-model="recordForm.remark"
						type="textarea"
						:rows="4"
						placeholder="请输入处理备注">
					</el-input>
				</el-form-item>
				<el-form-item label="解决方案" prop="solution" v-if="recordForm.action === 'SOLVE'">
					<el-input
						v-model="recordForm.solution"
						type="textarea"
						:rows="6"
						placeholder="请输入解决方案">
					</el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="addRecordDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleAddRecord" :loading="addRecordLoading">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import {
	getExceptionHandlingHistory,
	addHandlingRecord
} from '@/api/exceptionHandling'

export default {
	name: 'ExceptionDetail',
	props: {
		exceptionData: {
			type: Object,
			required: true
		}
	},
	data() {
		return {
			// 处理记录
			handlingRecords: [],

			// 相关异常
			relatedExceptions: [],

			// 展开状态
			messageExpanded: false,
			stackExpanded: false,

			// 格式化后的请求参数
			formattedParams: '',

			// 添加处理记录对话框
			addRecordDialogVisible: false,
			addRecordLoading: false,
			recordForm: {
				action: 'ANALYZE',
				remark: '',
				solution: ''
			},
			recordFormRules: {
				action: [
					{ required: true, message: '请选择处理动作', trigger: 'change' }
				],
				remark: [
					{ required: true, message: '请输入处理备注', trigger: 'blur' }
				],
				solution: [
					{ required: true, message: '请输入解决方案', trigger: 'blur' }
				]
			}
		}
	},

	created() {
		this.loadHandlingHistory()
		this.formatRequestParams()
		this.loadRelatedExceptions()
	},

	methods: {
		// 加载处理历史
		async loadHandlingHistory() {
			try {
				const response = await getExceptionHandlingHistory(this.exceptionData.id)
				if (response.code === 200) {
					this.handlingRecords = response.data || []
				}
			} catch (error) {
				console.error('获取处理历史失败:', error)
			}
		},

		// 加载相关异常
		async loadRelatedExceptions() {
			try {
				// 这里可以根据异常类型、模块等信息查询相关异常
				// 暂时使用模拟数据
				this.relatedExceptions = []
			} catch (error) {
				console.error('获取相关异常失败:', error)
			}
		},

		// 格式化请求参数
		formatRequestParams() {
			try {
				if (this.exceptionData.requestParams) {
					this.formattedParams = JSON.stringify(JSON.parse(this.exceptionData.requestParams), null, 2)
				}
			} catch (error) {
				this.formattedParams = this.exceptionData.requestParams
			}
		},

		// 切换异常信息展开状态
		toggleMessageExpand() {
			this.messageExpanded = !this.messageExpanded
		},

		// 切换堆栈信息展开状态
		toggleStackExpand() {
			this.stackExpanded = !this.stackExpanded
		},

		// 复制堆栈信息
		copyStackTrace() {
			const textarea = document.createElement('textarea')
			textarea.value = this.exceptionData.stackTrace
			document.body.appendChild(textarea)
			textarea.select()
			document.execCommand('copy')
			document.body.removeChild(textarea)
			this.$message.success('复制成功')
		},

		// 显示添加处理记录对话框
		showAddRecordDialog() {
			this.addRecordDialogVisible = true
		},

		// 添加处理记录
		handleAddRecord() {
			this.$refs.recordFormRef.validate(async (valid) => {
				if (valid) {
					this.addRecordLoading = true
					try {
						const response = await addHandlingRecord(this.exceptionData.id, this.recordForm)
						if (response.code === 200) {
							this.$message.success('添加成功')
							this.addRecordDialogVisible = false
							this.loadHandlingHistory()
							this.$emit('refresh')
						} else {
							this.$message.error(response.message || '添加失败')
						}
					} catch (error) {
						console.error('添加处理记录失败:', error)
						this.$message.error('添加失败')
					} finally {
						this.addRecordLoading = false
					}
				}
			})
		},

		// 查看相关异常
		viewRelatedException(exception) {
			// 可以跳转到新页面或打开新对话框查看相关异常
			this.$emit('view-related', exception)
		},

		// 获取异常类型标签类型
		getExceptionTypeTagType(exceptionType) {
			const typeMap = {
				'SYSTEM': 'danger',
				'BUSINESS': 'warning',
				'PARAMETER': 'info',
				'PERMISSION': 'warning',
				'DATABASE': 'danger',
				'NETWORK': 'warning',
				'FILE': 'info',
				'OTHER': ''
			}
			return typeMap[exceptionType] || ''
		},

		// 获取异常类型标签
		getExceptionTypeLabel(exceptionType) {
			const typeMap = {
				'SYSTEM': '系统异常',
				'BUSINESS': '业务异常',
				'PARAMETER': '参数异常',
				'PERMISSION': '权限异常',
				'DATABASE': '数据库异常',
				'NETWORK': '网络异常',
				'FILE': '文件异常',
				'OTHER': '其他异常'
			}
			return typeMap[exceptionType] || exceptionType
		},

		// 获取异常级别标签类型
		getExceptionLevelTagType(exceptionLevel) {
			const levelMap = {
				'LOW': 'info',
				'MEDIUM': 'warning',
				'HIGH': 'danger',
				'CRITICAL': 'danger'
			}
			return levelMap[exceptionLevel] || ''
		},

		// 获取异常级别标签
		getExceptionLevelLabel(exceptionLevel) {
			const levelMap = {
				'LOW': '低',
				'MEDIUM': '中',
				'HIGH': '高',
				'CRITICAL': '严重'
			}
			return levelMap[exceptionLevel] || exceptionLevel
		},

		// 获取处理状态标签类型
		getHandleStatusTagType(handleStatus) {
			const statusMap = {
				'UNHANDLED': 'danger',
				'HANDLING': 'warning',
				'HANDLED': 'success'
			}
			return statusMap[handleStatus] || ''
		},

		// 获取处理状态标签
		getHandleStatusLabel(handleStatus) {
			const statusMap = {
				'UNHANDLED': '未处理',
				'HANDLING': '处理中',
				'HANDLED': '已处理'
			}
			return statusMap[handleStatus] || handleStatus
		},

		// 获取记录颜色
		getRecordColor(action) {
			const colorMap = {
				'CREATE': '#409EFF',
				'ANALYZE': '#E6A23C',
				'SOLVE': '#67C23A',
				'CLOSE': '#909399',
				'REOPEN': '#F56C6C'
			}
			return colorMap[action] || '#409EFF'
		},

		// 获取动作标签类型
		getActionTagType(action) {
			const typeMap = {
				'CREATE': 'primary',
				'ANALYZE': 'warning',
				'SOLVE': 'success',
				'CLOSE': 'info',
				'REOPEN': 'danger'
			}
			return typeMap[action] || 'primary'
		},

		// 获取动作标签
		getActionLabel(action) {
			const labelMap = {
				'CREATE': '创建',
				'ANALYZE': '分析',
				'SOLVE': '解决',
				'CLOSE': '关闭',
				'REOPEN': '重新打开'
			}
			return labelMap[action] || action
		},

		// 格式化日期时间
		formatDateTime(dateTime) {
			if (!dateTime) return '-'
			return new Date(dateTime).toLocaleString('zh-CN')
		}
	}
}
</script>

<style scoped>
.exception-detail {
	padding: 0;
}

.detail-card {
	margin-bottom: 20px;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.exception-message {
	background-color: #f8f9fa;
	border: 1px solid #e9ecef;
	border-radius: 4px;
	padding: 12px;
	font-family: 'Courier New', monospace;
	font-size: 13px;
	line-height: 1.5;
	max-height: 100px;
	overflow: hidden;
	position: relative;
}

.exception-message.expanded {
	max-height: none;
}

.stack-trace {
	background-color: #2d3748;
	color: #e2e8f0;
	border-radius: 4px;
	padding: 12px;
	font-family: 'Courier New', monospace;
	font-size: 12px;
	line-height: 1.4;
	max-height: 200px;
	overflow-y: auto;
}

.stack-trace.expanded {
	max-height: 400px;
}

.stack-trace pre {
	margin: 0;
	white-space: pre-wrap;
	word-wrap: break-word;
}

.request-params {
	background-color: #f8f9fa;
	border: 1px solid #e9ecef;
	border-radius: 4px;
	padding: 12px;
}

.request-params pre {
	margin: 0;
	font-family: 'Courier New', monospace;
	font-size: 13px;
	line-height: 1.5;
}

.record-content {
	margin-left: 10px;
}

.record-header {
	display: flex;
	align-items: center;
	gap: 10px;
	margin-bottom: 5px;
}

.record-user {
	font-weight: 500;
	color: #303133;
}

.record-remark {
	color: #606266;
	font-size: 13px;
	line-height: 1.5;
}

.solution-content {
	background-color: #f0f9ff;
	border: 1px solid #bfdbfe;
	border-radius: 4px;
	padding: 16px;
}

.solution-text {
	color: #1e40af;
	font-size: 14px;
	line-height: 1.6;
	margin-bottom: 10px;
}

.solution-meta {
	display: flex;
	justify-content: space-between;
	font-size: 12px;
	color: #64748b;
}

/* Element UI 样式调整 */
.el-descriptions {
	margin-bottom: 0;
}

.el-descriptions-item__label {
	font-weight: 500;
}

.el-timeline-item__timestamp {
	color: #909399;
	font-size: 12px;
}

.el-table {
	margin-top: 10px;
}

.el-dialog__body {
	padding: 20px;
}
</style>